import os
# parse_tracker.py
import os
import re
import json

def parse_script(file_path):
    """
    解析 Ren'Py 脚本，提取 label / menu / jump 形成剧情结构
    """
    storyline = {"labels": {}}
    current_label = None
    in_menu = False
    current_menu = {"options": []}

    with open(file_path, "r", encoding="utf-8") as f:
        lines = f.readlines()
    
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        
        # 跳过空行和注释
        if not line or line.startswith("#"):
            i += 1
            continue

        # 找 label
        m = re.match(r"label\s+(\w+):", line)
        if m:
            label_name = m.group(1)
            current_label = label_name
            storyline["labels"][current_label] = {"jumps": [], "menus": []}
            in_menu = False
            i += 1
            continue

        # 找 jump (但如果在 menu 中，跳过)
        m = re.match(r"jump\s+(\w+)", line)
        if m and current_label and not in_menu:
            target = m.group(1)
            storyline["labels"][current_label]["jumps"].append(target)
            i += 1
            continue

        # 找 menu 开始
        if line.startswith("menu:") and current_label:
            in_menu = True
            current_menu = {"options": []}
            i += 1
            continue

        # 处理 menu 内容
        if in_menu and current_label:
            # 检查选项行 (带引号的文本)
            option_match = re.match(r'\"(.+?)\":', line)
            if option_match:
                option_text = option_match.group(1)
                
                # 查找对应的 jump 语句 (可能在下一行或多行后)
                jump_target = None
                j = i + 1
                while j < len(lines):
                    jump_line = lines[j].strip()
                    jump_match = re.match(r"jump\s+(\w+)", jump_line)
                    if jump_match:
                        jump_target = jump_match.group(1)
                        # 标记这行已经被处理，避免重复解析
                        lines[j] = "# processed: " + lines[j]
                        break
                    # 如果遇到新的选项或menu结束，停止搜索
                    if re.match(r'\"(.+?)\":', jump_line) or jump_line == "menu:":
                        break
                    j += 1
                
                if jump_target:
                    current_menu["options"].append({
                        "text": option_text,
                        "jump": jump_target
                    })
            
            # 检查 menu 结束 (缩进减少或新的label)
            next_line_indented = False
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                # 检查下一行是否还有缩进（属于menu内部）
                if next_line and (next_line.startswith("    ") or next_line.startswith("\t")):
                    next_line_indented = True
            
            if not next_line_indented and line and not line.startswith("    ") and not line.startswith("\t") and not re.match(r'\"(.+?)\":', line):
                in_menu = False
                if current_menu["options"]:
                    storyline["labels"][current_label]["menus"].append(current_menu)
                current_menu = {"options": []}
            
            # 检查是否到了文件末尾或新的label
            if i + 1 >= len(lines) or re.match(r"label\s+(\w+):", lines[i + 1].strip()):
                in_menu = False
                if current_menu["options"]:
                    storyline["labels"][current_label]["menus"].append(current_menu)
                current_menu = {"options": []}
        
        i += 1

    # 处理最后一个可能未关闭的menu
    if in_menu and current_label and current_menu["options"]:
        storyline["labels"][current_label]["menus"].append(current_menu)

    return storyline


def save_storyline_to_json(storyline, output_file):
    """
    保存为 JSON 文件
    """
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(storyline, f, indent=4, ensure_ascii=False)